package com.vincent.webservicedemo.config;

import com.vincent.webservicedemo.service.HelloService;
import com.vincent.webservicedemo.util.FileCopyUtils;
import org.apache.axis2.transport.http.AxisServlet;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.xml.ws.Endpoint;
import java.io.IOException;

/**
 * @author vincent
 * @date 2019/2/22
 * @description cxf和axis2配置
 */
@Configuration
@Component
public class WebServiceConfig {
    private static Logger logger = LoggerFactory.getLogger(WebServiceConfig.class);
    @Autowired
    private Bus bus;
    @Autowired
    private HelloService helloService;

    /**
     * cxf配置，映射/webservice/*所有地址
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean cxfServlet() {
        return new ServletRegistrationBean(new CXFServlet(), "/webservice/*");
    }

    /**
     * 发布cxf的ws服务
     *
     * @return
     */
    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(bus, helloService);
        endpoint.publish("/helloService");
        return endpoint;
    }

    /**
     * axis2配置，除了映射地址外还必须设置services.xml文件地址
     * 其中services地址必须在resource的xxx/services/xxx/META-INF子目录中，否者会找不到
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean axisServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new AxisServlet());
        servletRegistrationBean.addUrlMappings("/axisws/*");
        //通过默认路径无法找到services.xml，这里需要指定一下路径，且必须是绝对路径
        String path = this.getClass().getResource("/WEB-INF").getPath();
        logger.info("path:{}", path);
        if (path.toLowerCase().startsWith("file:")) {
            path = path.substring(5);
        }
        //如果获得到的地址里有感叹号，说明文件在压缩包（jar包）中，Axis2无法正常使用，需要拷贝到jar包外
        if (path.contains("!")) {
            try {
                FileCopyUtils.copy("WEB-INF/services/myServices/META-INF/services.xml");
            } catch (IOException e) {
                e.printStackTrace();
            }
            path = path.substring(0, path.lastIndexOf("/", path.indexOf("!"))) + "/WEB-INF";
        }
        logger.info("final path:{}", path);
        servletRegistrationBean.addInitParameter("axis2.repository.path", path);
        servletRegistrationBean.setLoadOnStartup(1);
        return servletRegistrationBean;
    }
}
